﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using BIPorter.Common.BLL;
using BIPorter.Common.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace BIPorter.Common.DAL
{
    public class AccountDAL
    {
        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public AccountModel GetUserInfoTest(string userName)
        {
            return new AccountModel("孙龙飞", "Admin", "123456", "AA54961", "1");
        }


        //TODO 正式上线修改此方法
        /// <summary>
        /// 从数据库中获取人员信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public AccountModel GetUserInfo(string userName)
        {
            Database db = CommonHelper.CreateDataBase();
            AccountModel accountModel = null;
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT TOP 1 
               [EmpNo]
              ,[empname]
              ,[positionname]
              ,[levels]
              ,[Account]
              ,br.ManagerAccount --副总域账号
              ,br.Manager_UserName --副总姓名
              ,br.Manager_UserCode --副总工号
               FROM [CentaipRPT].[dbo].[BI_RoleRight] b left join [CentaipRPT].[dbo].[BI_Right] br  
               on b.Account=br.AreaManagerAccount or b.Account=br.DirectorAccount or  b.Account=br.ManagerAccount
             WHERE Account=@UserName");
            DbCommand cmd = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(cmd, "UserName", DbType.String, userName);
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    accountModel = ReaderBind(dataReader);
                }
            }
            return accountModel;
        }

        private AccountModel ReaderBind(IDataReader dataReader)
        {
            AccountModel AccountModel = new AccountModel
            {
                UserName = dataReader["Account"].ToString(),
                EmployeeId = dataReader["EmpNo"].ToString(),
                NickName = dataReader["empname"].ToString(),
                Role = dataReader["levels"].ToString()
            };

            if (dataReader["Manager_UserName"] != null)
            {
                AccountModel managerInfo = new AccountModel
               {
                UserName = dataReader["ManagerAccount"].ToString(),
                EmployeeId = dataReader["Manager_UserCode"].ToString(),
                NickName = dataReader["Manager_UserName"].ToString(),
                };

                AccountModel.ManagerInfo = managerInfo; //该用户上级副总 为获取数据方便
            }
            return AccountModel;
        }
    }
}
